package top.igotcha.chapter.chapter5;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Gotcha
 * @date 2021/3/9
 * @describe
 */
public class AccountCas implements Account {
    //使用原子整数
    private AtomicInteger balance;
    public AccountCas(int balance) {
        this.balance = new AtomicInteger(balance);
    }
    @Override
    public Integer getBalance() {
        //得到原子整数的值
        return balance.get();
    }
    @Override
    public void withdraw(Integer amount) {
        while(true) {
            //获得修改前的值
            int prev = balance.get();
            //获得修改后的值
            int next = prev-amount;
            //比较并设值
            if(balance.compareAndSet(prev, next)) {
                break;
            }
        }
        // 可以简化为下面的方法
        // balance.addAndGet(-1 * amount);
    }
}
